<template>
  <div>
    <Card>
      <p slot="title">个人成绩录入</p>
      <Table :columns="columns" :data="personalData">
        <template slot-scope="{ row, index }" slot="action">
          <Button type="primary" size="small" style="margin-right: 5px" @click="edit(index,row)">录入</Button>
        </template>
      </Table>
    </Card>
    <Card>
      <p slot="title">集体成绩录入</p>
      <Table :columns="columns" :data="collectiveData">
        <template slot-scope="{ row, index }" slot="action">
          <Button type="primary" size="small" style="margin-right: 5px" @click="edit(index,row)">修改</Button>
        </template>
      </Table>
    </Card>
    <Modal
      v-model="showModal">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>编辑学生成绩</span>
      </p>
      <div style="text-align:center">
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
          <FormItem label="学生成绩" prop="results">
            <Input v-model="formValidate.results" placeholder="请输入学生成绩" clearable />
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button type="primary" @click="handleSubmit('formValidate')">修改</Button>
        <Button @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
  export default {
    data () {
      //验证表单内容，成绩的有效性
      const validateResults = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('成绩不能为空！'));
        }
        var strP = /^\d+(\.\d+)?$/;//正则匹配是否是数字类型
        if (!strP.test(value)) {
          callback(new Error('请输入数字类型数据！'));
        } else {
          if (value < 0 || value > 100) {
            callback(new Error('成绩必须是0至100的数字'));
          } else {
            callback();
          }
        }
      };
      return {
        showModal: false,
        formValidate: {
          stu_id: null,
          item_id: null,
          results: null,
        },
        ruleValidate: {
          results: [
            { required: true, validator: validateResults, trigger: 'change' }
          ]
        },
        columns: [
          {
            title: '序号',
            type: 'index',
            width: 100,
            align: 'center'
          },
          {
            title: '姓名',
            key: 'u_name'
          },
          {
            title: '性别',
            key: 'u_sex',
            render: (h, params) => {
              return h("span", params.row.u_sex == '1' ? '男' : '女'); //包装到span标签里返回
            }
          },
          {
            title: '项目名称',
            key: 'i_name'
          },
          {
            title: '比赛时间',
            key: 'time',
            align: "center",
            render: (h, params) => {
              let newType = params.row.time; //获取数据库的时间戳
              if (newType == '') return h("span", ''); //包装到span标签里返回
              let date = new Date(parseInt(newType))
              let fmt = 'YYYY-mm-dd  HH:MM'
              let ret
              const opt = {
                'Y+': date.getFullYear().toString(), // 年
                'm+': (date.getMonth() + 1).toString(), // 月
                'd+': date.getDate().toString(), // 日
                'H+': date.getHours().toString(), // 时
                'M+': date.getMinutes().toString(), // 分
                'S+': date.getSeconds().toString() // 秒
                // 有其他格式化字符需求可以继续添加，必须转化成字符串
              }
              for (let k in opt) {
                ret = new RegExp('(' + k + ')').exec(fmt)
                if (ret) {
                  fmt = fmt.replace(
                    ret[1],
                    ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
                  )
                }
              }
              return h("span", fmt); //包装到span标签里返回
            }
          },
          {
            title: '成绩',
            key: 'results'
          },
          {
            title: '操作',
            slot: 'action',
            width: 150,
            align: 'center'
          }
        ],
        personalData: [],
        collectiveData: []
      }
    },
    //组件挂在的时候获取数据
    mounted () {
      // 页面加载时获取数据
      this.getData()
    },
    methods: {
      getData () {
        // 获取个人项目列表
        this.$axios.get('/user/getAllRanking?type=1')
          .then(res => {
            if (res.data.code == 200) {
              this.personalData = res.data.data
            }
          })
          .catch(err => {
            console.error(err);
          })
        // 获取集体项目列表
        this.$axios.get('/user/getAllRanking?type=0')
          .then(res => {
            if (res.data.code == 200) {
              this.collectiveData = res.data.data
            }
          })
          .catch(err => {
            console.error(err);
          })
      },
      //点击编辑的时候
      edit (index, row) {
        this.formValidate.stu_id = row.id
        this.formValidate.item_id = row.l_id
        this.formValidate.results = row.results
        this.showModal = true
      },
      //提交修改
      handleSubmit (name) {
        this.$refs[name].validate((valid) => {
          //如果表单验证通过
          if (valid) {
            //发送axios(ajax)请求
            this.$axios.post("/user/entryResults", `stu_id=${this.formValidate.stu_id}&item_id=${this.formValidate.item_id}&results=${this.formValidate.results}`)
              .then(res => {
                if (res.data.code == 200) {
                  this.getData()//更新数据
                  this.showModal = false  //关闭弹框
                  this.$Message.success('修改成功');
                  //通知排名和获奖名单更新数据
                  this.$emit('change', Math.random() * 1000)
                  return
                }
                this.$Message.error('修改失败');
              })
              .catch(err => {
                console.error(err);
                this.$Message.error('服务器出错');
              })
          } else {
            this.$Message.error('请填写成绩!');
          }
        })
      },
      //重置按钮
      handleReset (name) {
        this.$refs[name].resetFields();
      }
    },
  }
</script>
